
import UIKit
import WebKit
import WebViewJavascriptBridge
import RxSwift
import SnapKit
import Alamofire
import AdSupport


open class MainVC: UIViewController {
    deinit {
        if webView.uiDelegate != nil {
            webView.scrollView.delegate = nil
            webView.uiDelegate = nil
            webView.navigationDelegate = nil
            webView.configuration.userContentController.removeAllUserScripts()
            webView.removeObserver(self, forKeyPath: estimatedProgress)
        }
        NotificationCenter.default.removeObserver(self)            
    }
    var statusBarIsDefault: Bool = true {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }
    let bag = DisposeBag()
    /// 进度条标识
    private let estimatedProgress = "estimatedProgress"
    private var brige: WebViewJavascriptBridge?
    
    /// 顶部stateView
    lazy var stateView: UIView = {
        let view = UIView.init()
        view.backgroundColor = .white
        return view
    }()
    /// webView
    let webView: WKWebView = {
        let config = WKWebViewConfiguration()
        ///允许在线播放
        config.allowsInlineMediaPlayback = true
        let web = WKWebView.init(frame: .zero, configuration: config)
        return web
    }()
    /// 进度条
    lazy var progressView: UIProgressView = {
        let progeress = UIProgressView.init(progressViewStyle: UIProgressView.Style.default)
        progeress.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 2)
        progeress.progressTintColor = .yellow
        return progeress
    }()
    /// 空白页
    lazy var emptyView: EmptyView = {
        let view = EmptyView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight))
        view.retry = {[weak self] () in
            self?.getMsg()
        }
        return view
    }()
    private var realHost: String = ""
    var channelCode: String
    var viewcontrol: UIViewController?
    
    //MARK: - Override Methods
    public init(channelCode: String, viewcontrol: UIViewController?) {
        self.channelCode = channelCode
        self.viewcontrol = viewcontrol
        super.init(nibName: nil, bundle: nil)
        
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override open func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        if (UIDevice.current.model == "iPad" || Platform.isSimulator) && viewcontrol != nil {
            DispatchQueue.main.async {
                UIApplication.shared.keyWindow?.rootViewController = self.viewcontrol
            }
            return
        }
        config()
        creatUI()
        getMsg()
    }
    override open var prefersStatusBarHidden: Bool {
        return false
    }
    override open var preferredStatusBarStyle: UIStatusBarStyle {
        if statusBarIsDefault {
            return .default
        } else {
            return .lightContent
        }
    }
    //MARK: - Private Methods
    private func registerNativeFunctions() {
        registGetCookieFunction()
        registerSaveCookie()
    }
}

extension MainVC {
    private func getMsg() {
        Alamofire.request("https://vestprod.oss-cn-shenzhen.aliyuncs.com/vesthost.txt", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseString {[weak self] (responseUrl) in
            self?.realHost = String.init(data: responseUrl.data ?? Data(), encoding: String.Encoding.utf8) ?? "http://www.63chanmei.com"
            self?.getHost()
        }
    }
    private func jumpMark1 (data : [String : Any]) {
        let status = data["status"]
        if status as? Int == 0 {
            
        }
        BaseUrl = data["h5Url"] as? String ?? ""
        if data["fieldCol"] as? String == "black" {
            statusBarIsDefault = true
        } else if data["fieldCol"] as? String == "white" {
            statusBarIsDefault = false
        } else {
            statusBarIsDefault = true
        }
        if let bgcolor = data["backgroundCol"] as? String {
            stateView.backgroundColor = UIColor.init(hexString: bgcolor)
        }
        self.loadURL(BaseUrl)
        for view in (self.view.subviews) {
            if view is EmptyView {
                view.removeFromSuperview()
            }
        }
    }
    private func getHost() {
        let device = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        let infoDictionary = Bundle.main.infoDictionary!
        let ver = infoDictionary["CFBundleShortVersionString"] as? String ?? "1.0"
        let requestDic = [
            "vestCode" : channelCode,
            "channelCode" : "iOS",
            "version" : ver,
            "deviceId" : device
        ]
        Alamofire.request("\(realHost)/admin/client/vestSign.do", method: .get, parameters: requestDic, encoding: URLEncoding.default, headers: nil).responseJSON {[weak self] (response) in
            if response.result.error == nil {
                if let reslut = response.result.value as? [String: Any] {
                    print(reslut)
                    if let data = reslut["data"] as? [String : Any]  {
                        self?.jumpMark1(data: data)
                    }
                }
            } else {
                self?.view.addSubview(self?.emptyView ?? EmptyView())
            }
        }
    }
}

//MARK: - H5注册调用相关事件
extension MainVC {
    private func registGetCookieFunction() {
        brige?.registerHandler("getCookie", handler: { (data, responseCallback) in
            let cookie = UserDefaults.standard.value(forKey: "WKWebViewKCookieKey")
            responseCallback?(cookie)
        })
    }
    private func registerSaveCookie() {
        brige?.registerHandler("saveCookie", handler: { (data, responseCallback) in
            if let cookie = data {
                UserDefaults.standard.set(cookie, forKey: "WKWebViewKCookieKey")
                UserDefaults.standard.synchronize()
            }
        })
    }
    ///设置状态栏字体颜色
    private func registerStateStyle() {
        brige?.registerHandler("setStateColor", handler: {[weak self] (data, responseCallback) in
            if let color = data as? String {
                if color == "black" {
                    self?.statusBarIsDefault = true
                } else if color == "white" {
                    self?.statusBarIsDefault = false
                }
            }
        })
    }
}

//MARK: - webView基本配置相关
extension MainVC: UIGestureRecognizerDelegate {
    func config() {
        //禁用自动设置内边距
        automaticallyAdjustsScrollViewInsets = false
        //设置手势代理
        navigationController?.interactivePopGestureRecognizer?.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(webReload), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    func creatUI() {
        creatStateView()
        creatWebView()
        view.addSubview(progressView)
    }
    func creatStateView() {
        view.addSubview(stateView)
        stateView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(0)
            make.height.equalTo(statusBarH)
        }
    }
    private func creatWebView() {
        brige = WebViewJavascriptBridge.init(webView)
        webView.uiDelegate = self
        brige?.setWebViewDelegate(self)
        webView.backgroundColor = .white
        webView.addObserver(self, forKeyPath: estimatedProgress, options: NSKeyValueObservingOptions.new, context: nil)
        registerNativeFunctions()
        view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(0)
            make.top.equalTo(stateView.snp.bottom)
        }
    }
    /// 加载h5
    func loadURL(_ url: String) {
        if let urlStr = URL.init(string: url) {
            let request = URLRequest.init(url: urlStr, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10)
            webView.load(request)
        } else {
        }
    }
    private func setUserAgent() {
        let uiweb = UIWebView.init()
        let agent = "IOS_AGENT/2.0\(uiweb.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? "")"
        UserDefaults.standard.register(defaults: ["UserAgent": agent])
        UserDefaults.standard.synchronize()
    }
    
    private func reload() {
        if Double(UIDevice.current.systemVersion) ?? 0 > 9.0 , Double(UIDevice.current.systemVersion) ?? 0 < 10.0 {
            loadURL(BaseUrl)
        } else {
            webView.reload()
        }
    }
    
    ///OC里有这个。直接翻译过来的。不知道是不是原本需求
    @objc private func webReload() {
        webView.evaluateJavaScript("webViewCallUp()", completionHandler: { (result, error) in
            if error != nil {
            }
        })
    }
    @objc private func rightswipe(_ sender: UIButton) {
        webView.scrollView.scrollsToTop = false;
        webView.goBack()
    }
    
    /// 重写系统侧滑返回，解决wk在9.x版本可能出现的侧滑返回加载延迟问题
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        reload()
        return true
    }
    
    /// KVO监听更新进度条
    override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == estimatedProgress {
            if let obj = object as? WKWebView, obj == webView {
                progressView.alpha = 1
                progressView.setProgress(Float(webView.estimatedProgress), animated: true)
                if webView.estimatedProgress >= 1.0 {
                    UIView.animate(withDuration: 0.3, delay: 0.3, options: UIView.AnimationOptions.curveEaseOut, animations: { [weak self] () in
                        self?.progressView.alpha = 0
                        }, completion: {[weak self] (finish) in
                            self?.progressView.setProgress(0, animated: true)
                    })
                }
            }
        }
    }
    
}

//MARK: - webView代理协议相关
extension MainVC: WKUIDelegate, WKNavigationDelegate {
    //MARK: - WKNavigationDelegate
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if webView.title != "undefined" {
            self.title = webView.title
        }
    }
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let openurl = navigationAction.request.url {
            if "\(openurl)".contains("https://itunes.apple.com") {
                UIApplication.shared.openURL(openurl)
            }else if !"\(openurl)".hasPrefix("http") {
                UIApplication.shared.openURL(openurl)
            }
        }
        decisionHandler(.allow)
    }
    //MARK: - WKUIDelegate
    public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController.init(title: "提示", message: message, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction.init(title: "确认", style: UIAlertAction.Style.default, handler: { (action) in
            completionHandler()
        }))
        present(alert, animated: true, completion: nil)
        
    }
    public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController.init(title: "提示", message: message, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel, handler: { (action) in
            completionHandler(false)
        }))
        alert.addAction(UIAlertAction.init(title: "确认", style: UIAlertAction.Style.default, handler: { (action) in
            completionHandler(true)
        }))
        present(alert, animated: true, completion: nil)
    }
    public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController.init(title: prompt, message: "", preferredStyle: UIAlertController.Style.alert)
        alert.addTextField { (textField) in
            textField.text = defaultText
        }
        alert.addAction(UIAlertAction.init(title: "完成", style: UIAlertAction.Style.default, handler: { (action) in
            completionHandler(alert.textFields?.first?.text)
        }))
        present(alert, animated: true, completion: nil)
    }
    
}


enum ScreenSize {
    case retain_3_5
    case retain_4
    case retain_4_7
    case retain_5_5
    case retain_5_8
    case unknow
    
    static func size() -> (width: CGFloat, height: CGFloat) {
        let _height = UIScreen.main.bounds.height
        let _width  = UIScreen.main.bounds.width
        let width   = min(_height, _width)
        let height   = max(_height, _width)
        return (width, height)
    }
    
    init() {
        let width  = ScreenSize.size().width
        let height = ScreenSize.size().height
        if width == 320 && height == 480 {
            self = .retain_3_5
        }else if width == 320 && height == 568 {
            self = .retain_4
        }else if width == 375 && height == 667 {
            self = .retain_4_7
        }else if width == 414 && height == 736 {
            self = .retain_5_5
        }else if width == 375 && height >= 812 {
            self = .retain_5_8
        }else {
            self = .unknow
        }
    }
}
let screenWidth   = ScreenSize.size().width
let screenHeight  = ScreenSize.size().height
//let isIphoneX = (ScreenSize.init() == .retain_5_8)
let isIphoneX = UIApplication.shared.statusBarFrame.size.height > 20
let statusBarH = UIApplication.shared.statusBarFrame.size.height

struct Platform {
    static let isSimulator: Bool = {
        var isSim = false
        #if arch(i386) || arch(x86_64)
        isSim = true
        #endif
        return isSim
    }()
}

extension UIColor {
    public convenience init?(hexString: String) {
        let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (255, 0, 0, 0)
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
    
    var coreImageColor: CIColor {
        return CIColor(color: self)
    }
    
    var hex: UInt {
        let red = UInt(coreImageColor.red * 255 + 0.5)
        let green = UInt(coreImageColor.green * 255 + 0.5)
        let blue = UInt(coreImageColor.blue * 255 + 0.5)
        return (red << 16) | (green << 8) | blue
    }
}
